#!/bin/sh

set -e

NANNY="%(ClientBuilder.target_dir)/nanny.sh"
DAEMON="%(ClientBuilder.target_dir)/%(Client.binary_name)"
DAEMON_ARGS="--config=%(ClientBuilder.target_dir)/%(ClientBuilder.config_filename)"

# This package is designed to work on systems with init.d, upstart, and systemd.
case "$1" in
  configure\)
    /bin/chmod +x "${NANNY}"
    ${DAEMON} ${DAEMON_ARGS} "--install"

    if [ -x /sbin/initctl ] && /sbin/initctl version | /bin/grep -q upstart; then
      # Early versions of upstart didn't support restarting a service that
      # wasn't already running:
      # https://bugs.launchpad.net/ubuntu/+source/upstart/+bug/430883
      /usr/sbin/service %(ClientBuilder.package_name) stop 2>/dev/null || true
      /usr/sbin/service %(ClientBuilder.package_name) start 2>/dev/null
    elif [ -x /bin/systemctl ]; then
      # Systemd
      /bin/systemctl enable %(ClientBuilder.package_name)
      /bin/systemctl restart %(ClientBuilder.package_name)
    elif [ -x "/etc/init.d/%(ClientBuilder.package_name)" ]; then
      update-rc.d %(ClientBuilder.package_name) defaults >/dev/null
      invoke-rc.d %(ClientBuilder.package_name) start || exit $?
    fi
  ;;

  abort-upgrade|abort-remove|abort-deconfigure\)
  ;;

  *\)
    echo "postinst called with unknown argument \`$1'" >&2
    exit 1
  ;;
esac

exit 0
